// request.js

const axios = require('axios');

const instance = axios.create({
  baseURL: '',
  // timeout: 5000,
});

instance.interceptors.request.use(
  (config) => {
    // 请求拦截器
    // 在发送请求之前进行处理
    // config.headers['Authorization'] = 'Bearer token';
    return config;
  },
  (error) => {
    // 请求错误处理
    return Promise.reject(error);
  }
);

instance.interceptors.response.use(
  (response) => {
    // 响应拦截器
    // 对响应数据进行处理
    return response.data;
  },
  (error) => {
    // 响应错误处理
    return Promise.reject(error);
  }
);

async function get(url, params) {
  try {
    const response = await instance({
      method: 'GET',
      url: url,
      params: params,
    });

    return response;
  } catch (error) {
    throw error;
  }
}

async function post(url, data) {
  try {
    const response = await instance({
      method: 'POST',
      url: url,
      data: data,
    });

    return response;
  } catch (error) {
    throw error;
  }
}

async function put(url, data) {
  try {
    const response = await instance({
      method: 'PUT',
      url: url,
      data: data,
    });

    return response;
  } catch (error) {
    throw error;
  }
}

async function del(url) {
  try {
    const response = await instance({
      method: 'DELETE',
      url: url,
    });

    return response;
  } catch (error) {
    throw error;
  }
}

module.exports = {
  get,
  post,
  put,
  del,
  request: instance,
};
